package com.s.rpc.handler;

import com.s.rpc.ServiceRegistry;
import com.s.rpc.domain.RpcRequest;
import com.s.rpc.domain.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.Getter;
import lombok.Setter;

import java.lang.reflect.Method;

/**
 * @author ShenshenLuo
 * @email luoshenshen@buaa.edu.cn
 * @date 2025/5/11 14:45
 **/
public class RpcServerHandler extends SimpleChannelInboundHandler<Object> {

    @Setter
    @Getter
    private ServiceRegistry serviceRegistry;

    public RpcServerHandler(ServiceRegistry serviceRegistry) {
        this.serviceRegistry = serviceRegistry;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server received: ");
        RpcRequest request = (RpcRequest) msg;
        RpcResponse response = new RpcResponse();
        response.setRequestId(request.getRequestId());

        Object service = serviceRegistry.getService(request.getClassName());
        Method method = service.getClass().getMethod(
                request.getMethodName(),
                request.getParameterTypes());
        Object result = method.invoke(service, request.getParameters());
        response.setData(result);

        ctx.writeAndFlush(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}
